package com.qssoft.cqry.common.shardingsphere.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.qssoft.cqry.common.shardingsphere.ds.DataSourceAspect;
import com.qssoft.cqry.common.shardingsphere.ds.DynamicDSourceAnnotationAdvisor;
import com.qssoft.cqry.common.shardingsphere.ds.DynamicDSourceAnnotationInterceptor;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: cloud-cqry
 * @description: 分库分表注解配置
 * @author: HuaQiao.Deng
 * @create: 2021-01-29 14:20
 */
@Configuration
@ConditionalOnClass({DruidDataSource.class,ShardingRuleConfiguration.class})
@EnableConfigurationProperties(DataSourceProperties.class)
@ConditionalOnProperty(value = "sharding.enable",havingValue = "true",matchIfMissing = true)
@RequiredArgsConstructor
public class ShardingDataSourceAutoConfiguration {

    //TODO 强烈注意：Spring Boot 2.X 版本不再支持配置继承，多数据源的话每个数据源的所有配置都需要单独配置，否则配置不会生效
    //https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

    //@Bean
    //@ConditionalOnMissingBean(DataSourceAspect.class)
    public DataSourceAspect dataSourceAspect(){
        return new DataSourceAspect();
    }


    @Bean
    public DynamicDSourceAnnotationInterceptor dynamicDSourceAnnotationInterceptor(){
        return new DynamicDSourceAnnotationInterceptor();
    }

    @Bean
    public DynamicDSourceAnnotationAdvisor dynamicDSourceAnnotationAdvisor(){
        DynamicDSourceAnnotationInterceptor dsInterceptor = dynamicDSourceAnnotationInterceptor();
        return new DynamicDSourceAnnotationAdvisor(dsInterceptor);
    }
}
